package config

import (
	"CmdUtil/crypto_util"
	"gopkg.in/yaml.v2"
	"log"
	"os"
)

type Config struct {
	Cmd     string            `yaml:"cmd"`
	WorkDir string            `yaml:"work_dir"`
	Input   map[string]string `yaml:"input"`
	Encoded bool              `yaml:"encoded"`
}

func GetConfig(configPath string) Config {
	conf := Config{}
	data, err := os.ReadFile(configPath)
	if err != nil {
		log.Fatal(err)
	}
	err = yaml.Unmarshal(data, &conf)
	if err != nil {
		log.Fatal(err)
	}
	// 是否需要加密pwd
	if !conf.Encoded {
		for k, v := range conf.Input {
			conf.Input[k] = crypto_util.Encrypt(v)
		}
		conf.Encoded = true
		data, err = yaml.Marshal(conf)
		if err != nil {
			log.Fatal(err)
		}
		_ = os.WriteFile(configPath, data, os.ModePerm)
		return GetConfig(configPath)
	}
	for k, v := range conf.Input {
		conf.Input[k] = crypto_util.Decrypt(v)
	}
	return conf
}
